import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import {
  mergeHttpPostParamsInForm,
  mergeHttpPostParamsInJson,
  mergeHttpGetParams
} from "../util/http";
import { ResponseData, ResponseListData, ResponseKVData } from "../type/http";
import { KVAny } from "../type/kv";

@Injectable()
export class HttpProxyService {
  constructor(private httpClient: HttpClient) {}

  postFormProxy<T>(url: string, params: KVAny): Observable<T> {
    const mhp = mergeHttpPostParamsInForm(url, params);
    return this.httpClient.post<T>(mhp.url, mhp.params, mhp.options);
  }

  postJsonProxy<T>(url: string, params: KVAny): Observable<T> {
    const mhp = mergeHttpPostParamsInJson(url, params);
    return this.httpClient.post<T>(mhp.url, mhp.params, mhp.options);
  }

  getProxy<T>(url: string, params: KVAny): Observable<T> {
    const mhp = mergeHttpGetParams(url, params);
    return this.httpClient.get<T>(mhp.url, { params: mhp.params });
  }

  postDefaultFormProxy(url: string, params: KVAny): Observable<ResponseData> {
    return this.postFormProxy<ResponseData>(url, params);
  }

  postDefaultJsonProxy(url: string, params: KVAny): Observable<ResponseData> {
    return this.postJsonProxy<ResponseData>(url, params);
  }

  getDefaultProxy(url: string, params: KVAny): Observable<ResponseData> {
    return this.getProxy<ResponseData>(url, params);
  }

  postKVFormProxy<T>(
    url: string,
    params: KVAny
  ): Observable<ResponseKVData<T>> {
    return this.postFormProxy<ResponseKVData<T>>(url, params);
  }

  postKVJsonProxy<T>(
    url: string,
    params: KVAny
  ): Observable<ResponseKVData<T>> {
    return this.postJsonProxy<ResponseKVData<T>>(url, params);
  }

  getKVProxy<T>(url: string, params: KVAny): Observable<ResponseKVData<T>> {
    return this.getProxy<ResponseKVData<T>>(url, params);
  }

  postListFormProxy<T>(
    url: string,
    params: KVAny
  ): Observable<ResponseListData<T>> {
    return this.postFormProxy<ResponseListData<T>>(url, params);
  }

  postListJsonProxy<T>(
    url: string,
    params: KVAny
  ): Observable<ResponseListData<T>> {
    return this.postJsonProxy<ResponseListData<T>>(url, params);
  }

  getListProxy<T>(
    url: string,
    params: KVAny): Observable<ResponseListData<T>> {
    return this.getProxy<ResponseListData<T>>(url, params);
  }
}
